import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import request from '@/utils/request'

export const useUserStore = defineStore('userInfo', () => {
  const token = ref(localStorage.getItem('token') || '') // token
  // 用户信息
  const userInfo = ref(
    JSON.parse(localStorage.getItem('user')) || {
      id: '',
      username: '',
      password: '',
      name: '',
      email: '',
      gender: '',
      birthday: '',
      phone: '',
      address: '',
      money: ''
    }
  )

  // 存token，一小时内有效
  watch(token, () => {
    localStorage.setItem('token', token.value)
    localStorage.setItem('expiration', new Date().getTime() + 3600000) // 设置过期时间
  })

  // 存user，一小时内有效
  watch(userInfo, async () => {
    localStorage.setItem('user', JSON.stringify(userInfo.value))
  })

  const getToken = () => {
    return token.value
  }

  const setToken = (newToken) => {
    token.value = newToken
  }
  const removeToken = () => {
    token.value = ''
    localStorage.removeItem('token')
  }

  const setUserInfo = (newValue) => {
    userInfo.value = newValue
  }

  const clearUserInfo = () => {
    userInfo.value = ''
    localStorage.removeItem('user')
  }

  // 向后端发送请求，获取用户信息，更新状态仓库
  const requestUserInfo = async () => {
    const res = (await request.get(`/Main/${userInfo.value.id}`)).data
    // 转化为字符串
    res.data.gender = `${res.data.gender}`
    // 转化为yyyy-mm-dd格式
    const date = new Date(res.data.birthday)
    res.data.birthday = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    userInfo.value = {
      ...res.data,
      username: userInfo.value.username,
      password: userInfo.value.password
    }
    // 更新本地存储信息
    localStorage.setItem('user', JSON.stringify(userInfo.value))
  }

  // 更新密码
  const updatePassword = (newPassword) => {
    userInfo.value.password = newPassword
  }

  // 返回用户信息
  const getUserInfo = () => {
    requestUserInfo()
    return userInfo.value
  }

  return {
    getToken,
    setToken,
    removeToken,
    updatePassword,
    requestUserInfo,
    setUserInfo,
    getUserInfo,
    clearUserInfo
  }
})
